package com.hankol.newretail

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.Constants.*
import com.baselibrary.MessageBus
import com.baselibrary.adapter.MyOrderTabAdapter
import com.baselibrary.bean.MyOrderTabBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.load
import com.baselibrary.extension.toast
import com.baselibrary.manager.RecycleViewManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.utils.ARouterUtils.jump
import com.baselibrary.utils.EventBusUtils.sendNotify
import com.baselibrary.activity.BaseActivity
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.newretail.adapter.GoodsGiftPopAdapter
import com.hankol.newretail.adapter.details.GoodsCoverPopVpAdapter
import com.hankol.newretail.adapter.details.GoodsCoverVpAdapter
import com.hankol.newretail.adapter.details.GoodsDetailAdapter
import com.hankol.newretail.adapter.details.GoodsServerDesAdapter
import com.hankol.newretail.bean.goods_details.FictitiousPersonBean
import com.hankol.newretail.bean.goods_details.GoodsDetails
import com.hankol.newretail.bean.goods_details.GoodsDetailsBanner
import com.hankol.newretail.bean.goods_details.GoodsDetailsMultiBean
import com.hankol.newretail.databinding.ActivityGoodsDetailNewBinding
import com.hankol.newretail.fragment.GoodsNormsDialog
import com.hankol.newretail.fragment.GoodsPlantDialog
import com.hankol.newretail.utils.RetailDialogUtils
import com.hankol.newretail.utils.RetailPopUtils
import com.hankol.newretail.viewmodel.GoodsDetailViewModel
import com.hankol.newretail.widget.GoodsVideoView
import com.hanxiang.hankol.wxapi.WXManager

import com.meiqia.core.MQManager
import com.meiqia.core.bean.MQMessage
import com.meiqia.core.callback.OnGetMessageListCallback
import com.tencent.rtmp.TXVodPlayer
import com.transitionseverywhere.Slide
import com.transitionseverywhere.TransitionManager
import com.umeng.socialize.bean.SHARE_MEDIA
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @description 商品详情
 * @author 关忆北、
 * @time 2022/8/18 8:53 下午
 */
@Route(path = ActivityRouter.NEW_RETAIL.GOODS_DETAUILS)
class GoodsDetailActivity : BaseActivity(), View.OnClickListener, GoodsNormsDialog.OnCloseClickListener, GoodsDetailAdapter.OnCloseCallBack {
    private var spuId: Long = 0
    private var skuId: Long = 0
    private var jumpSource = "其他"
    private var mTotalDy: Int = 0
    private var scrollBy: Int = 0
    private var scrollYHeight = 0f
    private var mOldItemPost: Int = -1
    private var mGoodsDetails: GoodsDetails? = null
    private val mediaList: ArrayList<GoodsDetailsBanner> = arrayListOf()
    private var data: ArrayList<GoodsDetailsMultiBean> = arrayListOf()
    private var tempData: ArrayList<GoodsDetailsMultiBean> = arrayListOf()
    private lateinit var adapter: GoodsDetailAdapter
    private lateinit var driftVpAdapter: GoodsCoverVpAdapter
    private lateinit var viewModel: GoodsDetailViewModel
    private lateinit var binding: ActivityGoodsDetailNewBinding
    private lateinit var commonVodPlayer: TXVodPlayer//封面图、小图、弹窗，统一用一个，设置不同的播放view就行
    private val mGoodsPlantDialog: GoodsPlantDialog by lazy { GoodsPlantDialog() }
    private val mGoodsNormsDialog: GoodsNormsDialog by lazy { GoodsNormsDialog() }//选择规格
    private val mGoodsTabAdapter: MyOrderTabAdapter by lazy { MyOrderTabAdapter(2) }
    private var tabList: ArrayList<MyOrderTabBean> = arrayListOf()
    private val topSmoothScroller: RecycleViewManager.TopSmoothScroller by lazy { RecycleViewManager.TopSmoothScroller(applicationContext) }
    private var isCheckNeedPay = false
    private lateinit var needPayDialog: AlertDialog

    companion object {

    }

    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_goods_detail_new
    }

    override fun init() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        binding = getDataBinding()
        commonVodPlayer = TXVodPlayer(applicationContext);
        scrollYHeight = ScreenUtils.getScreenWidth(this) / Constants.GOODS_COVER_SCALE
        viewModel = getActivityViewModelProvider(this).get(GoodsDetailViewModel::class.java)
        adapter = GoodsDetailAdapter(this, viewModel, commonVodPlayer, scrollYHeight, emptyList())
        driftVpAdapter = GoodsCoverVpAdapter(this, commonVodPlayer)
        if (ARouterUtils.parseParams(intent.extras!!, GOODS_DETAIL_ID)[0].checkNotNull()) {
            spuId = ARouterUtils.parseParams(intent.extras!!, GOODS_DETAIL_ID)[0].toLong()
        }
        if (ARouterUtils.parseParams(intent.extras!!, GOODS_DETAIL_SOURCE)[0].checkNotNull()) {
            jumpSource = ARouterUtils.parseParams(intent.extras!!, GOODS_DETAIL_SOURCE)[0]
        }
        if (ARouterUtils.parseParams(intent.extras!!, GOODS_SKU_ID)[0].checkNotNull()) {
            skuId = ARouterUtils.parseParams(intent.extras!!, GOODS_SKU_ID)[0].toLong()
        }

        val layoutManager: LinearLayoutManager = object : LinearLayoutManager(applicationContext) {
            override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {
                super.smoothScrollToPosition(recyclerView, state, position)
                topSmoothScroller.targetPosition = position
                startSmoothScroll(topSmoothScroller)
            }
        }


        binding.rvHoverTitle.adapter = mGoodsTabAdapter
        binding.rvGoodsLayout.layoutManager = layoutManager
        initData()
        initObserve()
        initListener()
        binding.rvHoverTitle.alpha = 0f
        binding.rvHoverTitle.isEnabled = false
        binding.llTitle.setBackgroundColor(Color.argb(0, 255, 255, 255))
        viewModel.upHoverLocation(binding.gvvDetailsVideoHover, ScreenUtils.dip2px(applicationContext, 200f))

        val params: RelativeLayout.LayoutParams = binding.ivAnimCart.layoutParams as RelativeLayout.LayoutParams
        params.width = ScreenUtils.getScreenWidth()
        params.height = scrollYHeight.toInt()
        binding.ivAnimCart.layoutParams = params


    }

    fun initData() {
        showLoadingDialog()
        viewModel.reqGoodsDetails(spuId, skuId)
        binding.rvGoodsLayout.adapter = adapter
    }

    //埋点
    fun sensors(bean: GoodsDetails) {
        bean.let {
            if (it.seckillActProductExtDTO.checkNotNull()) {
                val dto =it.seckillActProductExtDTO!!
                SensorsDataManager.instance.seckillGoodsClick(
                    jumpSource, "${dto?.seckillActId}", dto?.seckillActName.checkValue(), if (TimeUtil.getCurrentTimeMillis().minus(dto.stime) > 0) "进行中" else "待开始", "${dto?.spuId}", it.name.checkValue(), it.shopInfo.name.checkValue()
                )
            }
        }
    }

    private var isScor: Boolean = false
    fun initListener() {
        adapter.setOnCloseCallBack(this)
        adapter.setClickButtonBack(object : GoodsDetailAdapter.ClickButtonListener {
            override fun onClickButton(status: Int, position: Int, actId: Int) {
                when (status) {
                    1 -> viewModel.reqSeckillCancelSubscribe(actId.toString())
                    2 -> viewModel.reqSeckillAddSubscribe(actId.toString())
                }
            }

        })
        mGoodsNormsDialog.setOnCloseClickListener(this)
        binding.tvGoodsDetCarAdd.setOnClickListener(this)
        binding.tvGoodsDetCarBuy.setOnClickListener(this)
        binding.llGoodsDetCustomerService.setOnClickListener(this)
        binding.llGoodsDetShopCart.setOnClickListener(this)
        binding.llGoodsDetailsShare.setOnClickListener(this)
        binding.llGoodsDetailsBack.setOnClickListener(this)
        binding.gvvDetailsVideoHover.setOnPlayCompleteCallBack {
            TransitionManager.beginDelayedTransition(binding.rlGoodsDetTransition, Slide(Gravity.RIGHT))
            binding.gvvDetailsVideoHover.visibility = View.GONE
        }
        binding.gvvDetailsVideoHover.setOnClickListener {
            binding.gvvDetailsVideoHover.stopPlay()
            val goodsCoverPopVpAdapter = GoodsCoverPopVpAdapter(this@GoodsDetailActivity, mediaList, adapter.coverVpAdapter?.goodsVideoView!!, 0)
            RetailPopUtils.goodsCoverPop(this@GoodsDetailActivity, goodsCoverPopVpAdapter, 0, object : GoodsCoverPopVpAdapter.OnItemClickListener {
                override fun onItemClick(gsvGoodsMedialVideo: GoodsVideoView?) {

                    gsvGoodsMedialVideo?.let { gsvGoodsMedialVideo ->
                        commonVodPlayer.pause()
                        binding.gvvDetailsVideoHover.mVodPlayer = commonVodPlayer
                        binding.gvvDetailsVideoHover.vodPlayer.setPlayerView(binding.gvvDetailsVideoHover.mTxclGoodsDetVideo)
                        binding.gvvDetailsVideoHover.isVoice.let { gsvGoodsMedialVideo.isVoice(it) }
                        binding.gvvDetailsVideoHover.vodPlayer?.resume()
                        binding.gvvDetailsVideoHover.upPlayView(true)
                        gsvGoodsMedialVideo.upPlayView(true)
                        gsvGoodsMedialVideo.visibilityCover()
                        gsvGoodsMedialVideo.setOnVoiceClickListener { b ->
                            binding.gvvDetailsVideoHover.isVoice = b
                        }
                    }
                }

            })
        }
        adapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.rv_goods_det_tag -> {
                    //弹窗服务
                    mGoodsDetails?.let {
                        val goodsServerDesAdapter = GoodsServerDesAdapter()
                        goodsServerDesAdapter.setNewData(it.mallTagDtoList)
                        RetailPopUtils.goodsServerPop(this@GoodsDetailActivity, goodsServerDesAdapter, null)
                    }
                }

                R.id.tv_gift -> {
                    //赠品优惠
                    mGoodsDetails?.let {
//                        val goodsServerDesAdapter = GoodsServerDesAdapter()
//                        goodsServerDesAdapter.setNewData(it.mallTagDtoList)
                        val goodsGiftAdapter = GoodsGiftPopAdapter()
                        goodsGiftAdapter.setNewData(it.giftData.mallProductGiftCommodityVos)
                        RetailPopUtils.goodsGiftPop(this@GoodsDetailActivity, goodsGiftAdapter, mGoodsDetails?.giftData)
                    }
                }

                R.id.ll_goods_det_coin -> {
                    val dictionary = SpUtils.getInstance().loadDictionaryrBean
                    val desc = dictionary.getByName_system("currencyRules")
                    RetailPopUtils.goodsServerPop(this, null, desc, "酒币规则")
                }

                R.id.tv_seckill_tip -> {
                    val hashMap = HashMap<String, Any>()
                    hashMap["shopId"] = mGoodsDetails?.shopInfo?.shopId!!
                    jump(ActivityRouter.WINE_CELLAR.WINCE_ALL_SECKILL, hashMap)
                }

                R.id.ll_goods_det_upgrade -> {
                    if (SpUtils.getInstance().isLogin) {
                        if (SpUtils.getInstance().loadUserBean.data.isFans == 1) {
                            //跳转粉丝中心
                            ARouterUtils.jump(ActivityRouter.MINE_CENTER.FANS_CENTER)
                        } else {//粉丝申请状态
                            viewModel.reqFansApplyDetail()
                        }
                    } else {
                        //去登录
                        AppManager.getAppManager().openLoginPage()
                    }
                }
                R.id.ll_goods_evaluating_more -> {
                    mGoodsPlantDialog.goodsId = spuId
                    mGoodsPlantDialog.show(supportFragmentManager, supportFragmentManager.fragments.toString())
                }
                R.id.ll_goods_all_appraise, R.id.tv_see_all_appraise -> {
                    val hashMap = HashMap<String, Any>()
                    hashMap["spuId"] = mGoodsDetails!!.spuId
                    jump(ActivityRouter.NEW_RETAIL.ALL_APPRAISE, hashMap)
                }
                R.id.round_hf -> {
                    mGoodsDetails?.let {
                        RetailPopUtils.goodsServerPop(this, null, it.horizontalBannerList[0].description, "酱酒极客，喝酣客")
                    }
                }
            }
        }

        binding.rvGoodsLayout.addOnScrollListener(object : RecyclerView.OnScrollListener() {


            @SuppressLint("RtlHardcoded")
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                scrollBy = dy
                mTotalDy -= dy
                val scrollY: Int = -mTotalDy
                when {
                    scrollY <= 0f -> {
                        binding.ivTabIndicator.alpha = 0f
                        binding.rvHoverTitle.alpha = 0f
                        binding.rvHoverTitle.isEnabled = false
                        binding.llTitle.setBackgroundColor(Color.argb(0, 255, 255, 255))
                        binding.rvGoodsLayout.setPadding(0, 0, 0, 0)
                    }
                    scrollY <= scrollYHeight -> {
                        val scale: Float = scrollY / scrollYHeight
                        val alpha = 255 * scale
                        binding.rvHoverTitle.alpha = scale
                        binding.ivTabIndicator.alpha = scale
                        binding.rvHoverTitle.isEnabled = true
                        binding.llTitle.setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
                        //开始封面图的视频播放，前提是上滑时处于视频播放状态
                        viewModel.hideShowyView(binding, commonVodPlayer, adapter.coverVpAdapter, false)
                        adapter.scrollNavy?.let {
                            if (!it.isSelected) {
                                viewModel.startAuto(it)
                                it.isSelected = true
                            }
                        }
                        binding.rvGoodsLayout.setPadding(0, binding.llTitle.measuredHeight * scale.toInt(), 0, 0)
                    }
                    else -> {
                        binding.rvGoodsLayout.setPadding(0, binding.llTitle.measuredHeight, 0, 0)
                        binding.rvHoverTitle.alpha = 1f
                        binding.ivTabIndicator.alpha = 1f
                        binding.rvHoverTitle.isEnabled = true
                        binding.llTitle.setBackgroundColor(Color.argb(255, 255, 255, 255))
                        //结束视频封面图的播放
                        viewModel.showShowyView(binding, commonVodPlayer, adapter.coverVpAdapter)
                        adapter.scrollNavy?.isSelected = false
                        viewModel.stopAuto()
                    }
                }
                val mFirstVisibleItems = (binding.rvGoodsLayout.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
                if (mOldItemPost != mFirstVisibleItems) {
                    mOldItemPost = mFirstVisibleItems
                    mGoodsTabAdapter.upSelectedTab(mOldItemPost)
                }

            }

        })

        mGoodsTabAdapter.setOnItemClickListener { adapter, view, position ->
            binding.rvGoodsLayout.smoothScrollToPosition(position)
            mGoodsTabAdapter.upSelectedTab(position)
        }

        mGoodsTabAdapter.setOnLoadItemViewCallBack(object : MyOrderTabAdapter.OnLoadItemViewCallBack {

            override fun onSelectedDrawComplete(view: View, position: Int) {
                view.post {
                    //TransitionManager.beginDelayedTransition(binding.rlGoodsDetTransition)
                    val params: LinearLayout.LayoutParams = binding.ivTabIndicator.layoutParams as LinearLayout.LayoutParams
                    params.setMargins(view.left + view.width / 2, view.top, 0, 0)
                    binding.ivTabIndicator.layoutParams = params
                }
            }

        })
    }

    private fun initObserve() {
        viewModel.shopCartNumLD.observe(this, Observer {
            if (it.checkNotNull()) {
                if (it.count > 0) {
                    binding.tvGoodsDetCarAmount.visibility = View.VISIBLE
                    CommonUtil.formatNum99(binding.tvGoodsDetCarAmount, it.count)
                } else {
                    binding.tvGoodsDetCarAmount.visibility = View.GONE
                }
            }
        })

        viewModel.seckillAddSubLD.observe(this, Observer {
            if (it.checkNotNull()) {
                val goodsDetails = adapter.data[0].getSpecialBean() as GoodsDetails
                goodsDetails.seckillActProductExtDTO?.subscribeFlg = 1
                adapter.notifyItemChanged(0)
                PopUtils.showSeckillInternetSuccessDialog(this, TimeUtil.setYearMonthDay(it.stime), "${it.subscribeRemind}")
            }
        })

        viewModel.seckillCancelSubLD.observe(this, Observer {
            val goodsDetails = adapter.data[0].getSpecialBean() as GoodsDetails
            goodsDetails.seckillActProductExtDTO?.subscribeFlg = 0
            adapter.notifyItemChanged(0)
            "取消预约成功".toast()
        })

        viewModel.goodsDetailsLD.observe(this, Observer {
            hideLoadingDialog()
            if (it != null) {
                if (it.goodsStatus == 0) {
                    //埋点
                    sensors(it)
                    SensorsDataManager.instance.productVisit(jumpSource, it.spuId.toString(), if (it.shopInfo == null) "酣客总社" else it.shopInfo.name.checkValue(), it.name.checkValue(), it.cname.checkValue(), AmountUtil.changeF2Y(viewModel.getDefFansPrice(it).toString()))
                    this.mGoodsDetails = it
                    if (isCheckNeedPay) {
                        if (it.waitPayOrderList.checkNotNull()) {
                            needPayDialog = RetailDialogUtils.showNeedPayDialog(this, it.waitPayOrderList[0])
                            adapter.notifyDataSetChanged()
                        }
                        isCheckNeedPay = false
                        return@Observer
                    }
                    if (it.addShopCartPower == 0) {
                        binding.tvGoodsDetCarAdd.visibility = View.INVISIBLE
                    } else {
                        binding.tvGoodsDetCarAdd.visibility = View.VISIBLE
                    }

                    //购买按钮状态：0正常，1限定仅会员购买，2限定仅粉丝购买，3无库存
                    if (it.buyBtnStatus == 3) {
                        binding.tvGoodsDetCarBuy.text = "已抢光"
                        binding.tvGoodsDetCarAdd.visibility = View.INVISIBLE
                        binding.tvGoodsDetCarBuy.setBackgroundResource(R.drawable.shape_f54d53_alpha50_solid_4dp)
                    } else if (it.buyBtnStatus == 1 || it.buyBtnStatus == 2) {

                        if (it.buyBtnStatus == 1) {
                            if (SpUtils.getInstance().isFans) {
                                binding.tvGoodsDetCarBuy.text = "限定购买"
                                binding.tvGoodsDetCarBuy.setBackgroundResource(R.drawable.shape_f54d53_alpha50_solid_4dp)
                                binding.tvGoodsDetCarAdd.visibility = View.INVISIBLE

                            } else {
                                binding.tvGoodsDetCarBuy.text = "立即购买"
                            }
                        }
                        if (it.buyBtnStatus == 2) {
                            if (SpUtils.getInstance().isFans) {
                                binding.tvGoodsDetCarBuy.text = "立即购买"
                            } else {
                                binding.tvGoodsDetCarBuy.text = "限定购买"
                                binding.tvGoodsDetCarBuy.setBackgroundResource(R.drawable.shape_f54d53_alpha50_solid_4dp)
                                binding.tvGoodsDetCarAdd.visibility = View.INVISIBLE
                            }
                        }
                    } else {
                        binding.tvGoodsDetCarBuy.text = "立即购买"
                    }

                    binding.tvGoodsDetCarBuy.visibility = View.VISIBLE

                    val mGoodsDetailsMultiBean = GoodsDetailsMultiBean(GoodsDetailsMultiBean.TYPE_1, it)
                    data.add(mGoodsDetailsMultiBean)
                    binding.ivAnimCart.load(applicationContext, it.covers[0])
                    binding.ivAnimCart.visibility = View.GONE
                    tabList.add(MyOrderTabBean("商品", true))
                    if (it.daManReview.checkNotNull()) {
                        adapter.evaluateCount(it.daManReview.size)
                        val mDaManBean = GoodsDetailsMultiBean(GoodsDetailsMultiBean.TYPE_2, it.daManReview)
                        data.add(mDaManBean)
                        tabList.add(MyOrderTabBean("评测", false))
                    }
                    mGoodsTabAdapter.setNewData(tabList)
                    if (it.videos.checkNotNull()) {
                        for (index in it.videos.indices) {
                            val goodsBanner = GoodsDetailsBanner()
                            goodsBanner.video = it.videos[index].url
                            goodsBanner.cover = it.videos[index].cover
                            goodsBanner.coverType = GoodsDetailsBanner.GOODS_BANNER_VIDEO
                            mediaList.add(goodsBanner)
                        }
                    }
                    driftVpAdapter.setData(mediaList)

                    if (it.waterTipsPower == 1 && it.buyBtnStatus != 3) {
                        val readLocalJson = AppManager.readLocalJson(applicationContext, "fictitious_person.json")
                        val fictitiousPersonBean = GsonUtils.parseJsonToBean(readLocalJson, FictitiousPersonBean::class.java)
                        if (fictitiousPersonBean!=null&&fictitiousPersonBean.data.checkNotNull()) {
                            adapter.setFictitiousPerson(fictitiousPersonBean.data)
                        }
                    }

                    adapter.setmGoodsName(it.name)
                    adapter.setGoodsDetail(mGoodsDetails!!)
                    this.skuId = viewModel.getDefSku(it)
                    viewModel.reqGoodsGiftData(skuId.toInt(), it.spuId)
                    viewModel.reqGoodsGrassShow(spuId, 1)
                    if (it.waitPayOrderList.checkNotNull()) {
                        needPayDialog = RetailDialogUtils.showNeedPayDialog(this, it.waitPayOrderList[0])
                    }
                } else {
                    hideLoadingDialog()
                    adapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_GOODS_DETAIL, binding.rvGoodsLayout, "商品已下架")
                    binding.llGoodsDetCustomerService.visibility = View.INVISIBLE
                    binding.llGoodsDetShopCart.visibility = View.INVISIBLE
                    binding.llGoodsDetailsShare.visibility = View.INVISIBLE
                }
            }

        })
        viewModel.goodsGiftLD.observe(this, Observer { it ->
            if (it != null) {
                if (adapter.data.isEmpty() && data[0].itemType == GoodsDetailsMultiBean.TYPE_1) {//刚进入详情页的操作
                    val goodsDetails: GoodsDetails = data[0].getSpecialBean() as GoodsDetails
                    goodsDetails.giftData = it
                    adapter.setNewData(data)
                    hideLoadingDialog()
                } else if (adapter.data[0].itemType == GoodsDetailsMultiBean.TYPE_1) {//点选规格时的操作
                    val goodsDetails: GoodsDetails = adapter.data[0].getSpecialBean() as GoodsDetails
                    goodsDetails.giftData = it
                    adapter.notifyItemChanged(0)
                }
            } else {
                adapter.setNewData(data)
                hideLoadingDialog()
            }
        })

        viewModel.goodsGrassShow.observe(this, Observer { it ->
            if (it != null && it.data.isNotEmpty()) {
                adapter.grassShowCount(it.totalCount)
                val grassShowBean = GoodsDetailsMultiBean(GoodsDetailsMultiBean.TYPE_3, it.data)
                tempData.add(grassShowBean)
                tabList.add(MyOrderTabBean("种草", false))
            }
            viewModel.reqGoodsEvaluation(spuId, 1)

        })
        viewModel.goodsEvaluationLD.observe(this, Observer { it ->
            if (it.data.checkNotNull()) {
                adapter.appraiseCount(it.totalCount)
                val grassShowBean = GoodsDetailsMultiBean(GoodsDetailsMultiBean.TYPE_4, it.data)
                tempData.add(grassShowBean)
                tabList.add(MyOrderTabBean("评价", false))
            }
            mGoodsDetails?.let {
                if (it.desc.isNotEmpty()) {
                    val mDesBean = GoodsDetailsMultiBean(GoodsDetailsMultiBean.TYPE_5, it)
                    tempData.add(mDesBean)
                    tabList.add(MyOrderTabBean("详情", false))
                }
                if (it.shopInfo.checkNotNull()) {
                    viewModel.reqGoodsRecommend("[${spuId}]", 1, it.shopInfo.shopId, 1)
                } else {
                    viewModel.reqGoodsRecommend("[${spuId}]", 1, 0, 1)
                }
            }

        })
        viewModel.goodsRecommendLD.observe(this, Observer {
            if (it.data.checkNotNull()) {
                adapter.recommendCount(it.totalCount)
                val mRecommendBean = GoodsDetailsMultiBean(GoodsDetailsMultiBean.TYPE_6, it.data)
                tempData.add(mRecommendBean)
                tabList.add(MyOrderTabBean("精选", false))
            }
            adapter.addData(tempData)
            mGoodsTabAdapter.setNewData(tabList)
            binding.rvHoverTitle.layoutManager = GridLayoutManager(applicationContext, tabList.size)
        })
        viewModel.fansApplyLD.observe(this, Observer {
            if (it.checkNotNull()) {
                //审核状态
                ARouterUtils.jump(Constants.FANS_GIFT_APPLY_STATUS)
            } else {
                //跳转粉丝申请
                ARouterUtils.jump(Constants.FANS_GIFT_CORE)
            }
        })
    }

    override fun onClick(p0: View) {
        when (p0.id) {
            R.id.ll_goods_details_share -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage() //去登录
                    return
                }
                shareOption()

            }
            R.id.ll_goods_details_back -> {
                finish()
            }

            R.id.tv_goods_det_car_add -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage() //去登录
                    return
                }
                mGoodsNormsDialog.goodsId = spuId
                mGoodsNormsDialog.skuId = skuId
                mGoodsNormsDialog.normsType = GoodsNormsDialog.NORMS_SHOP_CART
                try {
                    mGoodsNormsDialog.show(supportFragmentManager, supportFragmentManager.fragments.toString())
                } catch (e: Exception) {
                }
            }
            R.id.tv_goods_det_car_buy -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage() //去登录
                    return
                }
                mGoodsDetails?.let {
                    if (it.buyBtnStatus == 3) {
                        ToastUtils.showShort(applicationContext, "商品补货中")
                        return
                    }

                    if (it.buyBtnStatus == 1) {
                        //1限定仅会员购买，
                        if (SpUtils.getInstance().isFans) {
                            ToastUtils.showShort(applicationContext, it.buyPolicyText)
                            return
                        }
                    }
                    if (it.buyBtnStatus == 2) {
                        //2限定仅粉丝购买
                        if (!SpUtils.getInstance().isFans) {
                            ToastUtils.showShort(applicationContext, it.buyPolicyText)
                            return
                        }
                    }
                }
                mGoodsNormsDialog.goodsId = spuId
                mGoodsNormsDialog.skuId = skuId
                mGoodsNormsDialog.normsType = GoodsNormsDialog.NORMS_SHOP_GOODS
                try {
                    mGoodsNormsDialog.show(supportFragmentManager, supportFragmentManager.fragments.toString())
                } catch (e: Exception) {
                }
            }
            R.id.ll_goods_det_customer_service -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage() //去登录
                    return
                }
                //客服
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    jump(ActivityRouter.MINE_CENTER.CUSTOMER_SERVICE, this)
                    binding.tvGoodsDetServerAmount.postDelayed(Runnable { sendNotify(MessageBus.msgId_hide_meiqia_red_dot) }, 1000)
                }
            }
            R.id.ll_goods_det_shop_cart -> {
                if (!SpUtils.getInstance().isLogin) {
                    AppManager.getAppManager().openLoginPage() //去登录
                    return
                }
                //购物车
                SensorsDataManager.instance.shopCartSee("商品详情页")
                val map = HashMap<String, Any>()
                map[Constants.SHOP_CART_SOURCE] = "商品详情页"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.SHOP_CART, map)
            }
        }
    }

    private fun shareOption() {
        PopUtils.showBottomSharePosterExe(this, object : PopUtils.IBottomShareWxExePosterCallBack {
            override fun clickWxExe() {
                mGoodsDetails?.let {
                    if (it.shareWxAppQrImgUrl.checkNotNull()) {
                        //分享小程序
                        WXManager. shareToWxExe(this@GoodsDetailActivity, Config.MINI_PROGRAM_ID, "${Config.MINI_PROGRAM_PAGE_PATH_GOODS_DETAIL}${it.spuId}", "${it?.name.checkValue()}", it?.name.checkValue(), it.shareLinkUrl, it.covers[0].checkValue())
                    } else {
                        //分享网页
                        UMShareUtils.shareWeb(this@GoodsDetailActivity, SHARE_MEDIA.WEIXIN, it.shareLinkUrl, it.covers[0].checkValue(), it?.name.checkValue(), it?.desc.checkValue())
                    }
                }
            }

            override fun clickPoster() {
                //海报分享
                mGoodsDetails?.let {
                    viewModel.goodsPosterShare(this@GoodsDetailActivity, it, it.shareLinkUrl)
                }
            }
        })
    }

    override fun onCloseClick() {
        mGoodsNormsDialog.dismiss()
    }

    override fun onClickImgCover(url: String) {
        binding.ivAnimCart.load(applicationContext, url)
    }

    override fun onAddCartClick(num: Int) {

        viewModel.addCartAnimation(binding.rlGoodsDetTransition, binding.ivAnimCart, binding.llGoodsDetShopCart, this@GoodsDetailActivity)

        if (num > 0) {
            binding.tvGoodsDetCarAmount.visibility = View.VISIBLE
            CommonUtil.formatNum99(binding.tvGoodsDetCarAmount, num)
        } else {
            binding.tvGoodsDetCarAmount.visibility = View.GONE
        }
        mGoodsNormsDialog.dismiss()
    }

    override fun onClickSpec(fansPrice: Long, price: Long, seckillFansPrice: Long, seckillPrice: Long,skuId: Long) {
        if (adapter.data[0].itemType == GoodsDetailsMultiBean.TYPE_1) {
            val goodsDetails: GoodsDetails = adapter.data[0].getSpecialBean() as GoodsDetails
            goodsDetails.hasSelectSpec = true
            goodsDetails.selectedFansPrice = fansPrice
            goodsDetails.selectedPrice = price
            goodsDetails.selectedSeckillFansPrice = seckillFansPrice
            goodsDetails.selectedSeckillPrice = seckillPrice
            adapter.notifyItemChanged(0)
            viewModel.reqGoodsGiftData(skuId.toInt(), spuId.toInt())
            this.skuId = skuId
        }

    }

    override fun onResume() {
        super.onResume()
        checkLocationInfo()
        getUnreadMsgNum()
        viewModel.reqShopCartNum()
    }

    private fun checkLocationInfo() {
        if (true) {
            if (CommonUtil.isLocationEnabled(this)) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    if (SpUtils.getFloat(ContextUtils.getCurApplication(), "address_Lat", 0f) == 0f) {
                        adapter.notifyItemChanged(0)
                    }
                }
            }
        }
    }

    //客服未读数量
    private fun getUnreadMsgNum() {
        MQManager.getInstance(this).getUnreadMessages(object : OnGetMessageListCallback {
            override fun onFailure(i: Int, s: String) {
                CommonUtil.formatNum99(binding.tvGoodsDetServerAmount, i)
                binding.tvGoodsDetServerAmount.visibility = if (i == 0) View.GONE else View.VISIBLE
            }

            override fun onSuccess(list: List<MQMessage>) {}
        })
    }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN) fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_mei_qia_have_new_msg) {
            getUnreadMsgNum()
        } else if (messageBus.codeType == MessageBus.msgId_location_permission_apply) {
            PermissionsUtils.getInstance().chekPermissions(this, PermissionCollection.LOCATION.getPermissionList(), object : PermissionsCall() {
                override fun permissionsPass() {
                    //权限通过
                    EventBusUtils.sendNotify(MessageBus.msgId_location_permission_pass)
                }

                override fun permissionsRefuse(strPer: java.util.ArrayList<String>) {

                }
            })
        } else if (messageBus.codeType == MessageBus.msgid_location_succ_refresh) {
            adapter.notifyItemChanged(0)
        } else if (messageBus.codeType == MessageBus.msgId_order_cancel_success || messageBus.codeType == MessageBus.msgId_pay_success) {
            if (needPayDialog != null && needPayDialog.isShowing) {
                needPayDialog.dismiss()
            }
        } else if (messageBus.codeType == MessageBus.msgId_refresh_goods_detail) {
            isCheckNeedPay = true
            viewModel.reqGoodsDetails(spuId, skuId)
        } else if (messageBus.codeType == MessageBus.msgId_refresh_seckill_sub_status) {
            val bean = adapter.data[0].getSpecialBean() as GoodsDetails
            if (bean.seckillActProductExtDTO != null) {
                if (bean.seckillActProductExtDTO?.subscribeFlg == 0) {
                    bean.seckillActProductExtDTO?.subscribeFlg = 1
                } else {
                    bean.seckillActProductExtDTO?.subscribeFlg = 0
                }
            }
            adapter.notifyItemChanged(0)

        }
    }

    override fun onPause() {
        super.onPause()
        viewModel.stopPlay(adapter)
        binding.gvvDetailsVideoHover.stopPlay()
    }

    override fun onRestart() {
        super.onRestart()
        adapter.scrollNavy?.let {
            it.isSelected = true
            viewModel.startAuto(it)
        }
    }

    override fun onStop() {
        super.onStop()
        viewModel.stopAuto()
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        viewModel.stopPlay(adapter)
        super.onDestroy()
    }

    /**
     * 从详情进入其他界面，隐藏视频弹窗
     */
    override fun onCloseCall() {
        //binding.gvvDetailsVideoHover.visibility = View.GONE
        //开始封面图的视频播放，前提是上滑时处于视频播放状态
        binding.gvvDetailsVideoHover.post {
            if (binding.gvvDetailsVideoHover.visibility == View.VISIBLE) {
                viewModel.hideShowyView(binding, commonVodPlayer, adapter.coverVpAdapter, true)
                adapter.coverVpAdapter?.goodsVideoView?.upPlayView(false)
            }
        }
    }


}